package ltd.nullpointer.frontend.tcp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boot2.core.utils.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import ltd.nullpointer.tcp.core.ServerMessageEncoder;
import ltd.nullpointer.tcp.core.message.AbstractMQTTMessage;
import ltd.nullpointer.tcp.core.serialize.ServerNPiotTCPMessageSerializer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 
 * @ClassName: MqttMessageEncoder
 * @Description: mqtt 消息编码器
 * @author zhangweilin
 * @date 2017年11月9日 下午1:25:39
 *
 */
@Component
public class MqttMessageEncoder extends MessageToByteEncoder<AbstractMQTTMessage> {
	public Log log = LogFactory.getLog(this.getClass());

//	@Autowired
//	DeviceJpaDao deviceJpaDao;
//
//	@Autowired
//	ProtocolItemJpaDao protocolItemJpaDao;

	@Autowired
	ServerMessageEncoder serverMessageEncoder;

	@Autowired
	ServerNPiotTCPMessageSerializer serverNPiotTCPMessageSerializer;

	@Override
	public void encode(ChannelHandlerContext ctx, AbstractMQTTMessage abstractMQTTMessage, ByteBuf out) throws Exception {
		StringBuffer sb = new StringBuffer();
		String msgCode = abstractMQTTMessage.getMsgCode();
		Integer msgSn = abstractMQTTMessage.getMsgSn();
		// 此时的abstractMQTTMessage可能是页面上通过spring
		// mvc接收的，也可能是自己通过fastjson手动转的，如果是前者，payload为json字符串，如果是后者，则payload为JSONObject
		JSONObject jsonObject = null;
		Object obj = abstractMQTTMessage.getPayload();
		System.out.println("obj: " + obj);
		if (obj instanceof String) {
			jsonObject = JSON.parseObject((String) obj);
			// jsonObject = jsonObject.getJSONObject("payload");
		} else {
			jsonObject = (JSONObject) obj;
		}

		if (null == jsonObject) {
			throw new Exception("payload不能为空");
		}
		System.out.println("jsonObject: " + jsonObject);
		String deviceId = jsonObject.getString("deviceId");
		if (StringUtils.isEmpty(deviceId)) {
			throw new Exception("deviceId不能为空");
		}

		sb.append(StringUtils.leftPad(msgCode + "", 3, "0"));
		sb.append(StringUtils.leftPad(msgSn + "", 2, "0"));
		sb.append(deviceId.length());
		sb.append(deviceId);
		sb.append("2");

		// ByteBuffer messageByteBuffer =
		// ByteBuffer.allocate(String.valueOf(msgCode).getBytes("UTF-8").byteLength);
		String str = serverNPiotTCPMessageSerializer.serializeDataMapToString(deviceId, msgCode, jsonObject);
		System.out.println("MqttMessageEncoder , 字节解析出字符串,str: " + str);
		byte[] mqttPayloadByte = str.getBytes("UTF-8");
		out.writeBytes(mqttPayloadByte);
		// AbstractTCPMessage abstractTCPMessage=new AbstractTCPMessage();
		// abstractTCPMessage.setPayloadByte(mqttPayloadByte);
		// serverMessageEncoder.encode(ctx, abstractTCPMessage, out);
		// ByteBuf copy = out.retainedDuplicate();
		// int len = copy.readableBytes();
		// byte[] bytes = new byte[len];
		// copy.readBytes(bytes);
	}
}
